package com.fesine.controller;

import com.fesine.entity.User;
import com.fesine.util.CryptographyUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Fesine on 2016/6/13.
 */

/**
 * 用户Controller层
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/user")
public class UserController{
    Logger logger = Logger.getLogger(UserController.class);

    /**
     * 用户登录
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        System.out.println("login do post");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String isRemembered = request.getParameter("isRemembered");
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
           return "index";//请求转发
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, CryptographyUtil.md5(password,"fesine"));
        try {
            //当选中记住我时，设置记住我为true
            if ("on".equals(isRemembered)) {
                if (subject.isRemembered()) {
                    logger.info("-----isRemembered-----");
                } else {
                    token.setRememberMe(true);
                }
            } else {
                token.setRememberMe(false);
            }
            subject.login(token);//验证登录信息，调用自定义realm
            Session session = subject.getSession();//获取session
            logger.info("sessionId:" + session.getId());
            logger.info("sessionHost:" + session.getHost());
            logger.info("sessionTimeout:" + session.getTimeout());
            session.setAttribute("info", "session的数据");//向前端输出数据
            return "redirect:/success.jsp";//重定向跳转到success.jsp
        } catch (UnknownAccountException e) {
            logger.info("用户名不存在！");
            request.setAttribute("userName", userName);
            request.setAttribute("password", password);
            request.setAttribute("errorInfo", "用户名不存在！");
            return "index";//请求转发
        } catch (IncorrectCredentialsException e) {
            logger.info("密码输入不正确！");
            request.setAttribute("userName", userName);
            request.setAttribute("password", password);
            request.setAttribute("errorInfo", "密码输入不正确！");
            return "index";//请求转发
        }
    }

}
